
cap drop kspillsown 
cap drop ctrystock ctryflow
cap drop own_spillover_contribution 
cap drop kowncontrib 

* sum up the patent counts (predicted if in simulation) across country-div-year by using the distributing inventor weight (divnearestsep)
*imported variable is depvar. generate a count in a country for the insample patents
gen depvar_weighted = `1' * weight_${iwvers}
bys ctry division year : egen count_insample = sum(depvar_weighted)

* multiply with out_sample multiplier to get the full county (note: when we run through this with data at the beginning, this gives us exactly the count_full)
gen ctrycount = count_insample * outsample_mult if year > 1995 & !missing(outsample_mult) 
replace ctrycount = max(count_insample, count_full) if year > 1995 & missing(outsample_mult)

* reduce to ctry-divison-year level, recompute country-level stocks beginning 1995 using counts & delta = 0.85 inventory method
preserve 
    *keep only one observation we dont need the rest
    keep ctry division year ctrycount data_ctrystock
    bys ctry division year ctrycount : gen x = _n
    keep if x == 1
    drop x

    *replace for the two year 1995 and 1996 as we do not simulate them 
    *1996 gets placed not in the first but in the second line!
    gen ctrystock = data_ctrystock if year == 1995 
    replace ctrystock = ctrycount if year > 1995

    *actual stock calculation
    bys ctry division (year) : replace ctrystock  = ctrystock + $deltadepreciation * ctrystock[_n-1] if _n > 1
    tempfile stocks
    save `stocks'
restore

* recompute country-level flows beginning 1995 and store flows at the ctry-divison-year level analogous to above
* just for comparison. 
preserve
*keep only one obs
    keep ctry division year ctrycount count_full
    bys ctry division year ctrycount : gen x = _n 
    keep if x == 1
    drop x

    *replace for the two year 1995 and 1996 as we do not simulate them 
    *1996 gets placed not in the first but in the second line!
    *note: this next line is the difference to the stocks calculation!
    *we replace 1995 not with stock but with the flow
    gen ctryflow = count_full if year == 1995 
    replace ctryflow = ctrycount if year > 1995
    drop ctrycount
    tempfile flows
    save `flows'
restore 

* merge stocks back in
mmerge ctry division year using `stocks'
drop _m
mmerge ctry division year using `flows'
drop _m

*calculate the firms spillovers received from the countries using the receiving weights
gen ctrystock_wtd = ctrystock * weight_pre
bys firm_division year : egen kspillsown = sum(ctrystock_wtd)

*drop temporary variables
drop ctrycount depvar_weighted count_insample ctrystock_wtd